import React, { useState, useContext } from "react";
import { AppState } from "../App";
import { ethers } from "ethers";
import "../css/mainStyles.css";
import "../css/loader.css";
const Main = () => {
  const App = useContext(AppState);
  const [Amount, setAmount] = useState();
  const [loading, setLoading] = useState(false);

  const Contribute = async () => {
    try {
      setLoading(true);
      const tx = await App.Foundationcontract.sendMoney({
        value: ethers.utils.parseUnits(Amount, 0),
      });
      await tx.wait();
      alert("捐赠成功!");
      setAmount("");
    } catch (error) {
      if (
        error.message ===
        "MetaMask Tx Signature: User denied transaction signature."
      ) {
        alert(" 用户拒绝交易签名。");
      } else {
        console.log(error.message);
        alert("捐款必须大于100WEI");
      }
    }finally {
      setLoading(false); 
    }
  };
  return (
    <div className="contributor-container">
      {loading && <div className="loader"></div>}
      <section className="contributor-section">
        <div className="contributor-title">致捐赠者：</div>
        <p className="contributor-subtitle">
          听从你内心深处的微小声音，为一个好事做出一点贡献。
        </p>
        <div className="contributor-input-container">
          <span className="contributor-label">Amount in WEI</span>
          <input
            type="text"
            placeholder="Amount in WEI"
            className="contributor-input"
            value={Amount}
            onChange={(e) => setAmount(e.target.value)}
          />
          <button onClick={Contribute} className="contributor-button">
            Submit
          </button>
        </div>
      </section>
    </div>
  );
};

export default Main;
